package com.wiscamp.ninechapters.tags.infrastructure.mappers;

import com.wiscamp.ninechapters.tags.domain.models.KnowledgeTreePoint;
import com.wiscamp.ninechapters.tags.infrastructure.po.KnowledgePointView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;


/**
 * 学科知识点仓储对象
 *
 * @author yifeng
 */
@Repository
public interface KnowledgePointViewMapper extends JpaRepository<KnowledgePointView, Long>, JpaSpecificationExecutor<KnowledgePointView> {

    @Query(value = "select e from KnowledgePointView e where e.subjectId = :subjectId and e.pointCode = :pointCode")
    KnowledgePointView findByPointCode(String pointCode, long subjectId);

    @Query(value = "select e from KnowledgePointView e where e.subjectId = :subjectId and e.pointName = :pointName")
    Collection<KnowledgePointView> findListByPointName(String pointName, long subjectId);

    @Query(value = "select e from KnowledgePointView e where e.subjectId = :subjectId and e.pointName like :pointName order by e.pointLevel desc")
    Collection<KnowledgePointView> findListByNameContains(String pointName, long subjectId);

    @Query(value = "select e from KnowledgePointView e where e.subjectId = :subjectId")
    Collection<KnowledgePointView> findListBySubject(long subjectId);


    @Query("select new com.wiscamp.ninechapters.tags.domain.models.KnowledgeTreePoint(sp.pointId, spr.targetPointId, sp.pointName, sp.enabled) from KnowledgePointView sp left join KnowledgePointRelationPO spr on  sp.pointId = spr.sourcePointId where sp.subjectId = :subjectId and spr.relationTypeId = :aggregationTypeId order by sp.pointLevel, sp.pointName, sp.pointId")
    Collection<KnowledgeTreePoint> findKnowledgeTreePointsBySubject(long subjectId, int aggregationTypeId);

    @Query("select new com.wiscamp.ninechapters.tags.domain.models.KnowledgeTreePoint(sp.pointId, spr.targetPointId, sp.pointName, sp.enabled) from KnowledgePointView sp left join KnowledgePointRelationPO spr on  sp.pointId = spr.sourcePointId where sp.subjectId = :subjectId and sp.pointId in (:pointIds) and spr.relationTypeId = :aggregationTypeId order by sp.pointName, sp.pointId")
    Collection<KnowledgeTreePoint> findKnowledgeTreePointsByIds(long subjectId, Collection<Long> pointIds, int aggregationTypeId);


    // todo: 待定
    // 获取数学竞赛下的知识点
    @Query(value = "select e from KnowledgePointView e where e.subjectId = :subjectId and e.pointName like :pointName and e.pointId > 5180 order by e.pointLevel desc")
    Collection<KnowledgePointView> findPointsByNameForOM(String pointName, long subjectId);
}